#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include "subprojects/tedi2html/tedi2html.h"
#include "preprocessor.h"
#include "exception.h"
using namespace std;

/*
 * Check if entered file has:
 *   - Every "__" (list tag) has a ",," (end list tag)
 * Returns true if it's a valid tedi file.
 */
bool test_file(string file){
	stringstream file_stringstream(file);
	string line;
	int start_list = 0;
	int end_list = 0;
	while(getline(file_stringstream, line)){
		if(line[0] != '<'){
			size_t ul = line.find("__");
			if(ul != std::string::npos)
				++start_list;

			size_t ul_end = line.find(",,");
			if(ul_end != std::string::npos)
				++end_list;
		}
	}
	bool result = true;
	if(start_list != end_list)
		result = false;
	return result;
}

/*
 *  Load every file from '+' tag.
 */
string one_file(string file){
	string line;
	string text;
	ifstream reader(file);
	size_t slash = file.rfind("/");
	if(!reader)
		throw Invalid("File not loaded. Maybe file doesn't exist ", file);
	while(getline(reader, line)){
		if(line[0] != '+')
			text += line + "\n";
		else{
			line = line.erase(0, 1);

			if(slash != string::npos)
				line = file.substr(0, slash + 1) + line;
			
			ifstream include(line);
			string include_line;
			if(!include)
				throw Invalid("File not loaded. Maybe file doesn't exist ", line);
			while(getline(include, include_line))
				text += include_line + "\n";
			
			include.close();
		}
	}
	reader.close();
	return text;
}
